import 'package:calf_account/api/pass_api.dart';
import 'package:calf_account/model/pass_tag.dart';
import 'package:calf_account/model/password.dart';
import 'package:get/get.dart';

import 'state.dart';

class PassLogic extends GetxController {
  final PassState state = PassState();
  List<PasswordTag> tags = [];
  Map<int, PasswordTag> tagMaps = {};
  List<Password> passwords = [];

  late bool isLoading = false;

  /*长按的密码项Id*/
  late int longPressPassId = -1;

  /*显示的密码项Ids*/
  late Map<int, int> canShowPassIds = {};

  /*搜索的值*/
  late String _key = "";

  /*抽屉选中的tag*/
  final Map<int, int> _ckTagIds = {};

  ///页面渲染完成后加载数据
  @override
  void onReady() {
    renderTagView();
    renderListView();
  }

  ///改变搜索框值
  void changeSearchKey(String key) {
    _key = key;

    renderListView();
  }

  ///获取当前tag的选中状态
  bool getTagStatusById(int tagId) {
    return _ckTagIds.containsKey(tagId);
  }

  ///改变tag选择
  void changeTagCheck(int tagId, bool ck) {
    if (ck) {
      _ckTagIds[tagId] = 0;
    } else {
      _ckTagIds.remove(tagId);
    }

    update(["tagView"]);
    renderListView();
  }

  ///改变密码 显示/影藏
  void changeEyeStatus(int id) {
    if (canShowPassIds.containsKey(id)) {
      canShowPassIds.remove(id);
    } else {
      canShowPassIds[id] = 0;
    }
    update(["eyeBtn" + id.toString(), "eyeText" + id.toString()]);
  }

  ///改变密码项操作按钮 显示/影藏
  void changePassHandleStatus(int id) {
    int old = longPressPassId;
    longPressPassId = id;
    update(["passHandel" + id.toString()]);
    update(["passHandel" + old.toString()]);
  }

  ///渲染标签Tag
  void renderTagView() {
    if (isLoading) {
      Get.snackbar("别着急", "上一次操作都还没完成呢!");
      return;
    }

    isLoading = true;
    update(["tagView"]);

    PasswordApi.localLoadTags()
        .then((value) => {
              isLoading = false,
              tags = value,
              for (PasswordTag item in tags) {tagMaps[item.id] = item},
              update(["tagView"])
            })
        .catchError((error) => {
              isLoading = false,
              update(["tagView"]),
              Get.snackbar("加载数据异常", error)
            });
  }

  ///渲染列表
  void renderListView() {
    if (isLoading) {
      Get.snackbar("别着急", "上一次操作都还没完成呢!");
      return;
    }

    isLoading = true;
    update(["passListView"]);

    PasswordApi.localLoadPasswords(_ckTagIds.keys, _key)
        .then((value) => {
              isLoading = false,
              passwords = value,
              update(["passListView"])
            })
        .catchError((error) => {
              isLoading = false,
              update(["passListView"]),
              Get.snackbar("加载数据异常", error)
            });
  }
}
